/*
 * AddAddressServlet.java
 * 作用：处理用户添加新收货地址的请求。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.AddressDao;
import com.campustradingwall.model.Address;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/addAddress")
public class AddAddressServlet extends HttpServlet {
    private AddressDao addressDao = new AddressDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("user");
        String newAddressStr = request.getParameter("newAddress");

        if (newAddressStr != null && !newAddressStr.trim().isEmpty()) {
            Address address = new Address();
            address.setUserId(user.getId());
            address.setAddress(newAddressStr);
            // 在这个简单的系统中，我们不处理默认地址的复杂逻辑，新添加的就不是默认
            address.setDefault(false); 
            addressDao.addAddress(address);
            request.getSession().setAttribute("message", "新地址添加成功！");
        } else {
            request.getSession().setAttribute("message", "地址不能为空！");
        }

        response.sendRedirect(request.getContextPath() + "/user/profile");
    }
} 